import React from 'react'
import { StackActions } from 'react-navigation'
import BaseUserAvator from 'src/pageP/base/base-user-avator'
import { uploadImage } from 'src/utils/RequestAPI'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'

import { connect } from 'react-redux'
import { DO_REQUEST_SAVEUSERINFO_C_ACTION } from '@store/actions/userinfo'

const mapDispatchToProps = dispatch => ({
  updateUserInfoC (payload) {
    dispatch(DO_REQUEST_SAVEUSERINFO_C_ACTION(payload))
  }
})
@connect(
  ({ userinfo }) => ({
    userinfo
  }),
  mapDispatchToProps
)
class CUserAvator extends BaseUserAvator {
  constructor (props) {
    super(props)
    const { userName, gender, userAvator } = this.props.userinfo.C
    this.state = {
      ...this.state,
      userName,
      userAvator,
      gender
    }
  }

  gpBack = () => {
    this.props.navigation.goBack()
  }

  /**
   * 下一步
   * @private
   */
  nextButtonClick = () => {
    const { userAvator: uri, mime } = this.state
    if (!uri) {
      const { params: { firstLogin } = {} } = this.props.navigation.state || {}
      if (firstLogin) {
        this.props.navigation.goBack()
      } else {
        CommonToast('您还未选择新的头像')
      }
      return
    }
    if (!uri.startsWith('file:')) {
      this.props.navigation.goBack()
      return
    }
    ShowLoading()
    uploadImage({ params: { uri, mime, type: 'avatar' } })
      .then(res => {
        const userAvator = res.data
        const {
          userId,
          C: { id }
        } = this.props.userinfo
        const params = {
          id,
          userId,
          userAvator
        }
        return this.props.updateUserInfoC({ params })
      })
      .then(res => {
        this.props.navigation.goBack()
      })
      .finally(() => {
        DismissLoading()
      })
  }
}
export default CUserAvator
